package com.example.a1.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.a1.R;
import com.example.a1.model.Course;
import com.example.a1.util.GlideUtil;

import java.util.List;

public class CourseAdapter extends BaseAdapter {
    private Context context;
    private List<Course> courseList;
    private LayoutInflater inflater;

    public CourseAdapter(Context context, List<Course> courseList) {
        this.context = context;
        this.courseList = courseList;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return courseList.size();
    }

    @Override
    public Object getItem(int position) {
        return courseList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return courseList.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_course, parent, false);
            holder = new ViewHolder();
            holder.image = convertView.findViewById(R.id.course_image);
            holder.title = convertView.findViewById(R.id.course_title);
            holder.teacher = convertView.findViewById(R.id.course_teacher);
            holder.difficulty = convertView.findViewById(R.id.course_difficulty);
            holder.rating = convertView.findViewById(R.id.course_rating);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Course course = courseList.get(position);
        holder.title.setText(course.getTitle());
        holder.teacher.setText("讲师: " + course.getTeacher());
        holder.difficulty.setText("难度: " + course.getDifficulty());
        holder.rating.setText("评分: " + String.format("%.1f", course.getRating()));
        GlideUtil.loadImage(context, course.getImageUrl(), holder.image);

        return convertView;
    }

    static class ViewHolder {
        ImageView image;
        TextView title;
        TextView teacher;
        TextView difficulty;
        TextView rating;
    }
}